package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
//@RequestMapping("/login")
public class LoginController {
    @Resource
    private ThirdPartyFeignService thirdPartyFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MemberFeignService memberFeignService;
    /**
     * 发送验证码**
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        String redisCode = stringRedisTemplate.opsForValue()
                .get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotBlank(redisCode)){
           Long l=Long.parseLong(redisCode.split("-")[1]);
           if(System.currentTimeMillis()-l<1000*60){
               return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode()
                       , BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
           }
        }

        String code = UUID.randomUUID().toString().substring(0, 5);
        String codeFinal=code+"_"+System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone
                ,codeFinal,10, TimeUnit.SECONDS);
        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * 用户注册****
     * @param registerVo
     * @param bindingResult
     * @return
     */
    @PostMapping("/register")
    public R register(@Valid UserRegisterVo registerVo, BindingResult bindingResult
            , RedirectAttributes attributes) {
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(item -> {
                return item.getField();
            }, item -> {
                return item.getDefaultMessage();
            }));
            attributes.addFlashAttribute("errors",errors);
//            return "redirect:http://auth.cfmall.com/reg.html";
        }
        String code = registerVo.getCode();
        String redisCode=stringRedisTemplate.opsForValue()
                .get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        if(StringUtils.isNotBlank(redisCode)){
            if(code.equals(redisCode.split("-")[0])){
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                R register = memberFeignService.register(registerVo);
                if(register.getCode()==0){
//                    return "redirect:http://auth.cfmall.com/login.html";
                }else {
                    //注册失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg", new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
//                    return "redirect:http://auth.cfmall.com/reg.html";
                }
            }
            else {
                HashMap<String, String> error = new HashMap<>();
                error.put("code","验证码错误");
                attributes.addFlashAttribute("errors",error);
//                return "redirect:http://auth.cfmall.com/reg.html";
            }
        }else {
            HashMap<String, String> error = new HashMap<>();
            error.put("code","验证码过期");
            attributes.addFlashAttribute("errors",error);
//            return "redirect:http://auth.cfmall.com/reg.html";
        }
        return R.ok();
        //注册成功返回到登录页
//        return "redirect:/login.html";
    }

    @PostMapping("/login")
    public R login(UserLoginVo userLoginVo,RedirectAttributes redirectAttributes){
        R r=memberFeignService.login(userLoginVo);
        if(r.getCode()==0){
//            return "redirect:http://cfmall.com";
            return R.ok();
        }else {
            //注册失败
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>() {}));
            redirectAttributes.addFlashAttribute("errors", errors);
//                    return "redirect:http://auth.cfmall.com/login.html";
            return R.error();
        }
    }

}
